import React, { useEffect } from 'react';
import _ from 'lodash';
import { connect } from 'umi';
import Header from './components/header';
import Content from './components/content';
import DropWrapper from '../dropWrapper';
import styles from './index.less';

const DropCube = connect(
  ({ dataSelect, dropViewState }) => ({
    selectOptions: dataSelect.selectOptions,
    viewState: dropViewState.viewState,
  }),
  (dispatch) => ({
    initSelectDict: (payload) =>
      dispatch({ type: 'dataSelect/initItemSelectOptions', payload }),
    handleChangeCollapse: (payload) =>
      dispatch({ type: 'dropViewState/changeCollapse', payload }),
    handleCheckChange: (payload) =>
      dispatch({ type: 'dropViewState/checkChange', payload }),
    handleClearChecked: (payload) =>
      dispatch({ type: 'dropViewState/clearChecked', payload }),
    handleClearState: (payload) =>
      dispatch({ type: 'dropViewState/clearStateByDelete', payload }),
  }),
)(
  ({
    nanoid,
    id,
    label,
    pList,
    viewState,
    selectOptions,
    initSelectDict,
    handleDelete,
    handleChangeCollapse,
    handleCheckChange,
    handleClearState,
    handleClearChecked,
  }) => {
    const selectList = selectOptions[id] || [];
    const { collapsed, checkedList } = viewState[nanoid] || {};

    useEffect(() => {
      if (_.isEmpty(selectList)) {
        initSelectDict({ id })
          .then(() => {
            console.log('可勾选项初始化成功');
          })
          .catch(() => {
            console.log('可勾选项初始化失败');
          });
      }
    }, []);

    return (
      <div
        className={`${styles.cubeDropContent} ${
          collapsed ? styles.collapsed : null
        }`}
      >
        <Header
          nanoid={nanoid}
          label={label}
          collapsed={collapsed}
          checkedList={checkedList}
          handleDelete={handleDelete}
          handleChangeCollapse={handleChangeCollapse}
          handleClearState={handleClearState}
        />
        <Content
          nanoid={nanoid}
          label={label}
          pList={pList}
          selectList={selectList}
          checkedList={checkedList}
          handleCheckChange={handleCheckChange}
          handleClearChecked={handleClearChecked}
        />
      </div>
    );
  },
);

export default DropWrapper(DropCube);
